<?php
/**
 * XmuSlh, web platform of Student Association Federation of Xiamen University
 * 
 * Rewritting one or some pages of StatusNet. 
 * To get the original version, please visit <http://status.net/>.
 * 
 * StatusNet, the distributed open-source microblogging tool
 * 
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * An action that is a invisiable json action, meaning that it
 * returns json data whatever.
 * 
 * It uses to handle the ajax uploading picture from the client.
 * 
 * 用于接收并且处理Picture类文件AJAX上传的Action.
 * 
 * @author		ytukie <ytukie@gmail.com>
 * @version		0.1
 */

// XmuSlh only.
if ( !defined('XMUSLH')) { exit(1); }

// Requirements.
require_once INSTALLDIR . '/lib/slh_jsonaction.php';
require_once INSTALLDIR . '/lib/slh_util.php';

require_once INSTALLDIR . '/classes/Picture.php';

class UploadpicturejsonAction extends JsonAction
{
	/**
	 * The returning data items.
	 */
	var $status = '0';			// 0 error, 1 success
	var $error = '';			// set if status = 0
	var $picture_id = '0';		// id of the picture
	var $thumbnailurl = '';		// url of the uploaded thumbnail picture
	
	/**
	 * The uploaded picture_id. Delete it!
	 */
	var $uploadedpicture_id;
	
	/**
	 * Some initializations. Might block this request.
	 */
	function prepare($args)
	{
		if ( !Rights::hasRight(slh_get_userrights(), RIGHT_NEWS)) {
			return false;
		}
		
		parent::prepare($args);

		// Inits the jsondata.
		$this->jsondata['status'] = $this->status;
		$this->status =& $this->jsondata['status'];
		$this->jsondata['error'] = $this->error;
		$this->error =& $this->jsondata['error'];
		$this->jsondata['picture_id'] = $this->picture_id;
		$this->picture_id =& $this->jsondata['picture_id'];
		$this->jsondata['thumbnailurl'] = $this->thumbnailurl;
		$this->thumbnailurl =& $this->jsondata['thumbnailurl'];
		
		// Get the uploaded picture_id if uploaded before. Not 0.
		// Not so strict that some minded people mind change it.
		$this->uploadedpicture_id = $this->getTrimmedArg('guploadedpicture_id');

		return true;
	}
	
	/**
	 * Handle a request.
	 */
	function handle($args)
	{
		parent::handle($args);
		
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$this->handlePost();
		} else {
			slh_redirectto_default();
		}
		
		parent::showJson();
	}
	
	/**
	 * Handle a post, if a really picture uploading post.
	 */
	function handlePost()
	{
		// Workaround for PHP returning empty $_POST and $_FILES when POST
		// length > post_max_size in php.ini
		if (empty($_FILES) &&
			empty($_POST) &&
			($_SERVER['CONTENT_LENGTH'] > 0)) {
			// $this->jsondata['error'] = 'The server was unable to handle that mush POST data due to its current configuration.';
			$this->error = 'The server was unable to handle that mush POST data due to its current configuration.';
			return;
		}
		
		try {
			$picturefile = ImageFile::fromUpload('picturefile');
			
			if (null === $picturefile) {
				throw new Exception('No file uploaded.');
			}
			
			if ($picturefile->size > ImageFile::maxPhotoSizeInt()) {
				throw new Exception('Pass over the size limitation.');
			}
	
//TODO: the id		
			$news_id = 0; 
			$mimetype = $picturefile->preferredType();
			$filename = Picture::filename($news_id,
										  image_type_to_extension($mimetype),
										  uniqid());
			$filepath = Picture::path($filename);
			$picturefile->copyTo($filepath);
			
			// Add an thumbnail.
			$thumbnailname = Picture::filename2Thumbnailname($filename);
			$thumbnailpath = Picture::path($thumbnailname);
			$picturefile->pictureResize($thumbnailpath, 
										PICTURE_THUMBNAIL_MAXWIDTH,
										PICTURE_THUMBNAIL_MAXHEIGHT);
			
			// Adds into the database.
			$picture_id = Picture::add(array('news_id' => $news_id,
											 'picturename' => $filename,
											 'mimetype' => $mimetype,
											 'width' => $picturefile->width,
											 'height' => $picturefile->height));
			
			if ( !$picture_id) {
				// Try to delete the uploaded file.
				@unlink($filepath);
				@unlink($thumbnailpath);
					
				throw new Exception('添加' . $picturefile->name . '失败, 请重新尝试添加.');
			}
			
			// While a new picture is uploaded successfully, then check the old one!
			// See the uploadedpicture_id is existed already, then clear it up!
			Picture::removeIfAiredPicture($this->uploadedpicture_id);
			
			// Success. Set the json datas.
			$this->status = '1';
			$this->picture_id = $picture_id;
			$this->thumbnailurl = Picture::url($thumbnailname);
			
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			return;
		}
	}
}

?>